import 'package:check_app/dao/collectList_dao.dart';
import 'package:check_app/dao/input_dao.dart';
import 'package:check_app/model/taskInfo.dart';
import 'package:check_app/scoped_model/app_model.dart';
import 'package:check_app/util/pref_util.dart';
import 'package:check_app/util/uploadImage_util.dart';
import 'package:check_app/widgets/PictureOffline.dart';
import 'package:check_app/widgets/RadioSelect.dart';
import 'package:check_app/widgets/deleteModal.dart';
import 'package:check_app/widgets/downModal.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import 'package:scoped_model/scoped_model.dart';
import 'dart:convert' as convert;

class InputPage extends StatefulWidget {
  final String code;
  final int id;
  final int taskId;
  final int index;
  final int totalNumber;
  final int finishQuantity;
  final List subjectList;

  const InputPage({
    Key key,
    this.code,
    this.id,
    this.totalNumber,
    this.subjectList,
    this.finishQuantity,
    this.taskId,
    this.index,
  }) : super(key: key);
  @override
  State<StatefulWidget> createState() => new _InputPageState();
}

class _InputPageState extends State<InputPage> {
  bool _loading = false;
  TextEditingController _subName = new TextEditingController();
  TextEditingController _code = new TextEditingController();
  GlobalKey _formKey = new GlobalKey<FormState>();

  int currentIndex = 0;
  List collectList = [];
  List specList = [];
  List picUrlList = [];
  Map<String, TextEditingController> _controllers = Map();
  Map<String, String> _radioValue = Map();
  String verdictType;

  List<Map> jianyanList;

  @override
  void initState() {
    super.initState();
    currentIndex =
        widget.finishQuantity == widget.totalNumber ? 0 : widget.finishQuantity;
    jianyanList = [
      {
        'lable': '合格',
        'value': 'PASS',
      },
      {
        'lable': '不合格',
        'value': 'FAIL',
      },
    ];
    collectList = widget.subjectList;
    _subName.text = widget.subjectList[currentIndex].subName;
    _code.text = widget.subjectList[currentIndex].code;
    verdictType =
        widget.subjectList[currentIndex].verdictType ?? jianyanList[0]['value'];
    specList = widget.subjectList[currentIndex].specList;
    picUrlList = widget.subjectList[currentIndex].picUrlList ?? [];
    print('初始化数据');
    print(widget.subjectList[currentIndex].verdictType);
  }

  Future<Null> getData() async {
    setState(() {
      _loading = true;
    });
    try {
      var result = await CollectListDao.fetch(
          '/subject/collect/' + widget.id.toString() + '/list', {
        'collectId': widget.id.toString(),
      });
      setState(() {
        _loading = false;
      });
      if (result.success) {
        setState(() {
          collectList = result.data;
          _subName.text = result.data[currentIndex].subName;
          _code.text = result.data[currentIndex].code;
          verdictType =
              result.data[currentIndex].verdictType ?? jianyanList[0]['value'];
          specList = result.data[currentIndex].specList;
          picUrlList = result.data[currentIndex].picUrlList ?? [];
        });
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  Future<Null> getLocalData() async {
    final taskInfo =
        await PrefUtil().getString('task_' + widget.taskId.toString());
    final taskInfoModel = TaskInfo.fromJson(convert.jsonDecode(taskInfo));
    final subjectList =
        taskInfoModel.subjectCollectList[widget.index].subjectList;
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        collectList = subjectList;
        _subName.text = subjectList[currentIndex].subName;
        _code.text = subjectList[currentIndex].code;
        verdictType =
            subjectList[currentIndex].verdictType ?? jianyanList[0]['value'];
        specList = subjectList[currentIndex].specList;
        picUrlList = subjectList[currentIndex].picUrlList ?? [];
      });
    });
    print('获取本地数据更新');
    print(verdictType);
    return null;
  }

  Future<Null> saveInput(String type) async {
    final connectionStatus =
        ScopedModel.of<GlobalModel>(context).connectionStatus;
    if (connectionStatus == 'ConnectivityResult.none') {
      print('无信号');
      await saveInputLocal(type);
      return null;
    }
    print('有信号');
    setState(() {
      _loading = true;
    });
    try {
      var result = await InputDao.save({
        'id': collectList[currentIndex].id,
        'code': _code.text,
        'verdictType': verdictType ?? collectList[currentIndex].verdictType,
        'specList': handleData(),
        'picUrlList': picUrlList,
      });
      setState(() {
        _loading = false;
      });
      if (result.success) {
        final taskInfo =
            await PrefUtil().getString('task_' + widget.taskId.toString());

        if (taskInfo != null) {
          print(1);
          await saveInputLocal(type);
        } else {
          print(2);
          if (type == 'next') {
            collectList = [];
            specList = [];
            currentIndex = currentIndex + 1;
            verdictType = null;
            _controllers = Map();
            _radioValue = Map();
            getData();
          } else if (type == 'pre') {
            collectList = [];
            specList = [];
            currentIndex = currentIndex - 1;
            verdictType = null;
            _controllers = Map();
            _radioValue = Map();
            getData();
          } else if (type == 'done') {
            Navigator.of(context).pop();
          }
        }
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  Future<Null> saveInputLocal(String type) async {
    setState(() {
      _loading = true;
    });
    print('保存本地');
    final taskInfo =
        await PrefUtil().getString('task_' + widget.taskId.toString());

    if (taskInfo != null) {
      print('本地有任务数据');
      var taskInfoMap = convert.jsonDecode(taskInfo);
      taskInfoMap['subjectCollectList'][widget.index]['subjectList']
          [currentIndex]['code'] = _code.text;
      taskInfoMap['subjectCollectList'][widget.index]['subjectList']
              [currentIndex]['verdictType'] =
          verdictType ??
              taskInfoMap['subjectCollectList'][widget.index]['subjectList']
                  [currentIndex]['verdictType'];
      taskInfoMap['subjectCollectList'][widget.index]['subjectList']
          [currentIndex]['specList'] = handleData();
      taskInfoMap['subjectCollectList'][widget.index]['subjectList']
          [currentIndex]['picUrlList'] = picUrlList;
      print(taskInfoMap['subjectCollectList'][widget.index]['subjectList']
          [currentIndex]['verdictType']);

      final finishQuantity =
          taskInfoMap['subjectCollectList'][widget.index]['finishQuantity'];
      taskInfoMap['subjectCollectList'][widget.index]['finishQuantity'] =
          currentIndex + 1 > finishQuantity ? currentIndex + 1 : finishQuantity;
      await PrefUtil().setString(
          'task_' + widget.taskId.toString(), convert.jsonEncode(taskInfoMap));
    } else {
      print('本地无任务数据');
      final taskInfo = await PrefUtil().getString('taskInfo');
      var taskInfoMap = convert.jsonDecode(taskInfo);
      taskInfoMap['subjectCollectList'][widget.index]['subjectList']
          [currentIndex]['code'] = _code.text;
      taskInfoMap['subjectCollectList'][widget.index]['subjectList']
              [currentIndex]['verdictType'] =
          verdictType ??
              taskInfoMap['subjectCollectList'][widget.index]['subjectList']
                  [currentIndex]['verdictType'];
      taskInfoMap['subjectCollectList'][widget.index]['subjectList']
          [currentIndex]['specList'] = handleData();
      taskInfoMap['subjectCollectList'][widget.index]['subjectList']
          [currentIndex]['picUrlList'] = picUrlList;
      print(taskInfoMap['subjectCollectList'][widget.index]['subjectList']
          [currentIndex]['verdictType']);
      final finishQuantity =
          taskInfoMap['subjectCollectList'][widget.index]['finishQuantity'];
      taskInfoMap['subjectCollectList'][widget.index]['finishQuantity'] =
          currentIndex + 1 > finishQuantity ? currentIndex + 1 : finishQuantity;
      await PrefUtil().setString(
          'task_' + widget.taskId.toString(), convert.jsonEncode(taskInfoMap));
    }
    if (type == 'next') {
      collectList = [];
      specList = [];
      currentIndex = currentIndex + 1;
      verdictType = null;
      _controllers = Map();
      _radioValue = Map();
      getLocalData();
    } else if (type == 'pre') {
      collectList = [];
      specList = [];
      currentIndex = currentIndex - 1;
      verdictType = null;
      _controllers = Map();
      _radioValue = Map();
      getLocalData();
    } else if (type == 'done') {
      Navigator.of(context).pop();
    }
    setState(() {
      _loading = false;
    });
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Color.fromRGBO(248, 248, 249, 1),
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          centerTitle: true,
          title: Text((currentIndex + 1).toString() +
              '/' +
              widget.totalNumber.toString()),
        ),
        body: SafeArea(
          child: ModalProgressHUD(
            inAsyncCall: _loading,
            child: Stack(
              children: <Widget>[
                SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(top: 16),
                        decoration: BoxDecoration(
                          border: Border(
                            top: BorderSide(
                              width: 0.5,
                              color: Color.fromRGBO(229, 229, 229, 1),
                            ),
                          ),
                        ),
                        child: Form(
                          key: _formKey,
                          autovalidate: false,
                          child: Column(
                            children: <Widget>[
                              // 待检物编码
                              Container(
                                height: 62,
                                width: double.infinity,
                                padding: EdgeInsets.only(right: 16),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: Color.fromRGBO(255, 255, 255, 1),
                                  border: Border(
                                    bottom: BorderSide(
                                      width: 0.5,
                                      color: Color.fromRGBO(229, 229, 229, 1),
                                    ),
                                  ),
                                ),
                                child: Row(
                                  children: <Widget>[
                                    Container(
                                      width: 120,
                                      padding: EdgeInsets.only(left: 16),
                                      child: Text(
                                        '待检物编码',
                                        style: TextStyle(
                                          fontSize: 16,
                                          height: 19 / 16,
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: TextFormField(
                                        enabled: hasCode(),
                                        controller: _code,
                                        style: TextStyle(
                                          fontSize: 15.5,
                                          height: 22.5 / 15.5,
                                          color: Color.fromRGBO(43, 44, 46, 1),
                                        ),
                                        decoration: InputDecoration(
                                          fillColor: Colors.pink,
                                          contentPadding:
                                              EdgeInsets.fromLTRB(0, 0, 16, 0),
                                          hintText: "请扫描或输入待检物编码",
                                          hintStyle: TextStyle(
                                            fontSize: 15.5,
                                            height: 22.5 / 15.5,
                                            color: Color.fromRGBO(
                                                181, 184, 189, 1),
                                          ),
                                          border: OutlineInputBorder(
                                            borderSide: BorderSide.none,
                                          ),
                                        ),
                                        validator: (v) {
                                          return v.trim().length > 0
                                              ? null
                                              : '待检物编码不能为空';
                                        },
                                      ),
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        if (hasCode()) {
                                          qrscan();
                                        }
                                      },
                                      child: Image(
                                        image: AssetImage(
                                            'assets/images/scan.png'),
                                        width: 16,
                                        height: 16,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              // 待检物名称
                              Container(
                                height: 62,
                                width: double.infinity,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: Color.fromRGBO(255, 255, 255, 1),
                                  border: Border(
                                    bottom: BorderSide(
                                      width: 0.5,
                                      color: Color.fromRGBO(229, 229, 229, 1),
                                    ),
                                  ),
                                ),
                                child: Row(
                                  children: <Widget>[
                                    Container(
                                      width: 120,
                                      padding: EdgeInsets.only(left: 16),
                                      child: Text(
                                        '待检物名称',
                                        style: TextStyle(
                                          fontSize: 16,
                                          height: 19 / 16,
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: TextFormField(
                                        enabled: false,
                                        autofocus: false,
                                        controller: _subName,
                                        style: TextStyle(
                                          fontSize: 15.5,
                                          height: 22.5 / 15.5,
                                          color: Color.fromRGBO(43, 44, 46, 1),
                                        ),
                                        decoration: InputDecoration(
                                          fillColor: Colors.pink,
                                          contentPadding:
                                              EdgeInsets.fromLTRB(0, 0, 16, 0),
                                          hintText: "请输入待检物名称",
                                          hintStyle: TextStyle(
                                            fontSize: 15.5,
                                            height: 22.5 / 15.5,
                                            color: Color.fromRGBO(
                                                181, 184, 189, 1),
                                          ),
                                          border: OutlineInputBorder(
                                            borderSide: BorderSide.none,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              // 第二部分
                              Container(
                                child: Column(
                                  children: getList(specList),
                                ),
                              ),
                              verdictType != null
                                  ? RadioSelect(
                                      title: '检验结论',
                                      defaultvalue: verdictType,
                                      items: jianyanList,
                                      callback: (value) {
                                        verdictType = value['value'];
                                      },
                                    )
                                  : SizedBox(),
                              Container(
                                alignment: Alignment.centerLeft,
                                margin: EdgeInsets.fromLTRB(16, 12, 16, 8),
                                child: Text(
                                  '图片（选填）',
                                  style: TextStyle(
                                    fontSize: 14,
                                    height: 20 / 14,
                                    color: Color.fromRGBO(150, 151, 154, 1),
                                  ),
                                ),
                              ),
                              // 图片
                              Container(
                                padding: EdgeInsets.all(16),
                                decoration: BoxDecoration(
                                  color: Color.fromRGBO(255, 255, 255, 1),
                                  border: Border(
                                    top: BorderSide(
                                      width: 0.5,
                                      color: Color.fromRGBO(229, 229, 229, 1),
                                    ),
                                    bottom: BorderSide(
                                      width: 0.5,
                                      color: Color.fromRGBO(229, 229, 229, 1),
                                    ),
                                  ),
                                ),
                                child: Picture(
                                  count: 4,
                                  picList: picUrlList,
                                  onAdd: () {
                                    showModalBottomSheet(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return DownModal(
                                          cameraCb: () async {
                                            final connectionStatus =
                                                ScopedModel.of<GlobalModel>(
                                                        context)
                                                    .connectionStatus;
                                            if (connectionStatus ==
                                                'ConnectivityResult.none') {
                                              final url =
                                                  await UploadImageUtil()
                                                      .saveImageFromCamera();
                                              setState(() {
                                                picUrlList.add(url);
                                                _loading = false;
                                              });
                                            } else {
                                              final url =
                                                  await UploadImageUtil()
                                                      .getImageFromCamera();
                                              setState(() {
                                                picUrlList.add(url);
                                                _loading = false;
                                              });
                                            }
                                          },
                                          photoCb: () async {
                                            final connectionStatus =
                                                ScopedModel.of<GlobalModel>(
                                                        context)
                                                    .connectionStatus;
                                            if (connectionStatus ==
                                                'ConnectivityResult.none') {
                                              final urlList =
                                                  await UploadImageUtil()
                                                      .saveImageFromGallery(9 -
                                                          picUrlList.length);
                                              setState(() {
                                                for (var value in urlList) {
                                                  picUrlList
                                                      .add(value.toString());
                                                }
                                                _loading = false;
                                              });
                                            } else {
                                              final urlList =
                                                  await UploadImageUtil()
                                                      .loadAssets(9 -
                                                          picUrlList.length);
                                              setState(() {
                                                for (var value in urlList) {
                                                  picUrlList
                                                      .add(value.toString());
                                                }
                                                _loading = false;
                                              });
                                            }
                                          },
                                        );
                                      },
                                    );
                                  },
                                  onRemove: (url) {
                                    showModalBottomSheet(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return DeleteModal(
                                          onRemove: () {
                                            setState(() {
                                              picUrlList.remove(url);
                                            });
                                          },
                                        );
                                      },
                                    );
                                  },
                                ),
                              ),
                              getButton(),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                // Positioned(
                //   left: 0,
                //   right: 0,
                //   bottom: 20,
                //   child: getButton(),
                // ),
              ],
            ),
          ),
        ));
  }

  handleData() {
    return specList
        .map((item) => {
              "id": item.id,
              "key": item.key,
              "name": item.name,
              "options": item.options,
              "type": item.type,
              "value": getValue(item),
            })
        .toList();
  }

  getValue(item) {
    if (item.type == 'INPUT_DECIMAL') {
      return _controllers[item.key].text;
    } else {
      return _radioValue[item.key];
    }
  }

  hasCode() {
    if (collectList.length > 0) {
      return collectList[currentIndex].code == null ||
          collectList[currentIndex].code == '';
    } else {
      return true;
    }
  }

  strTolist(String str, String key) {
    var list = str.split(',');
    return list
        .map((item) => {'lable': item, 'value': item, 'key': key})
        .toList();
  }

  // 获取菜单项widget列表
  List<Widget> getList(List list) {
    return list.map<Widget>((item) => createItem(item)).toList();
  }

  // 生成���个菜单项
  Widget createItem(item) {
    if (item.type == 'INPUT_DECIMAL') {
      if (_controllers[item.key] == null) {
        _controllers[item.key] = TextEditingController(text: item.value ?? '');
      }
      return Container(
        height: 62,
        width: double.infinity,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Color.fromRGBO(255, 255, 255, 1),
          border: Border(
            bottom: BorderSide(
              width: 0.5,
              color: Color.fromRGBO(229, 229, 229, 1),
            ),
          ),
        ),
        child: Row(
          children: <Widget>[
            Container(
              width: 120,
              padding: EdgeInsets.only(left: 16),
              child: Text(
                item.name,
                style: TextStyle(
                  fontSize: 16,
                  height: 19 / 16,
                ),
              ),
            ),
            Expanded(
              child: TextFormField(
                autofocus: false,
                controller: _controllers[item.key],
                onChanged: (text) {},
                style: TextStyle(
                  fontSize: 15.5,
                  height: 22.5 / 15.5,
                  color: Color.fromRGBO(43, 44, 46, 1),
                ),
                decoration: InputDecoration(
                  fillColor: Colors.pink,
                  contentPadding: EdgeInsets.fromLTRB(0, 0, 16, 0),
                  hintText: '请输入' + item.name,
                  hintStyle: TextStyle(
                    fontSize: 15.5,
                    height: 22.5 / 15.5,
                    color: Color.fromRGBO(181, 184, 189, 1),
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                  ),
                ),
                inputFormatters: [
                  WhitelistingTextInputFormatter(RegExp("[0-9.]"))
                ],
                keyboardType: TextInputType.number,
                validator: (v) {
                  return v.trim().length > 0 ? null : (item.name + '不能为空');
                },
              ),
            ),
          ],
        ),
      );
    } else {
      _radioValue[item.key] =
          item.value ?? strTolist(item.options, item.key)[0]['value'];
      return RadioSelect(
        title: item.name,
        defaultvalue: item.value,
        items: strTolist(item.options, item.key),
        callback: (value) {
          _radioValue[value['key']] = value['value'];
        },
      );
    }
  }

  getButton() {
    if (widget.totalNumber == 1) {
      return Container(
        padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
        width: double.infinity,
        child: MaterialButton(
          onPressed: () async {
            if ((_formKey.currentState as FormState).validate()) {
              print('提交');
              final result =
                  await PrefUtil().openAlertDialog(context, '是否保存数据');
              if (result == 'ok') {
                saveInput('done');
              }
            }
          },
          color: Colors.blue,
          textColor: Colors.white,
          height: 44,
          child: Text(
            '提交',
            style: TextStyle(
              fontSize: 14,
              height: 24 / 17,
            ),
          ),
        ),
      );
    } else {
      if (currentIndex == 0) {
        return Container(
          padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
          width: double.infinity,
          child: MaterialButton(
            onPressed: () async {
              if ((_formKey.currentState as FormState).validate()) {
                print('提交');
                final result =
                    await PrefUtil().openAlertDialog(context, '是否保存数据');
                if (result == 'ok') {
                  saveInput('next');
                }
              }
            },
            color: Colors.blue,
            textColor: Colors.white,
            height: 44,
            child: Text(
              '下一条',
              style: TextStyle(
                fontSize: 14,
                height: 24 / 17,
              ),
            ),
          ),
        );
      } else if (currentIndex + 1 < widget.totalNumber) {
        return Container(
          padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
          width: double.infinity,
          child: Row(
            children: <Widget>[
              MaterialButton(
                onPressed: () async {
                  if ((_formKey.currentState as FormState).validate()) {
                    print('提交');
                    final result =
                        await PrefUtil().openAlertDialog(context, '是否保存数据');
                    if (result == 'ok') {
                      saveInput('pre');
                    }
                  }
                },
                color: Color.fromRGBO(248, 248, 249, 1),
                textColor: Color.fromRGBO(89, 131, 252, 1),
                height: 44,
                minWidth: 160,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(2)),
                  side: BorderSide(
                    width: 1,
                    color: Color.fromRGBO(89, 131, 252, 1),
                    style: BorderStyle.solid,
                  ),
                ),
                child: Text(
                  '上一条',
                  style: TextStyle(
                    fontSize: 14,
                    height: 24 / 17,
                  ),
                ),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.centerRight,
                  child: MaterialButton(
                    onPressed: () async {
                      if ((_formKey.currentState as FormState).validate()) {
                        print('提交');
                        final result =
                            await PrefUtil().openAlertDialog(context, '是否保存数据');
                        if (result == 'ok') {
                          saveInput('next');
                        }
                      }
                    },
                    color: Colors.blue,
                    textColor: Colors.white,
                    height: 44,
                    minWidth: 160,
                    child: Text(
                      '下一条',
                      style: TextStyle(
                        fontSize: 14,
                        height: 24 / 17,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      } else if (currentIndex + 1 == widget.totalNumber) {
        return Container(
          padding: EdgeInsets.fromLTRB(16, 16, 16, 16),
          width: double.infinity,
          child: Row(
            children: <Widget>[
              MaterialButton(
                onPressed: () async {
                  if ((_formKey.currentState as FormState).validate()) {
                    print('提交');
                    final result =
                        await PrefUtil().openAlertDialog(context, '是否保存数据');
                    if (result == 'ok') {
                      saveInput('pre');
                    }
                  }
                },
                color: Color.fromRGBO(248, 248, 249, 1),
                textColor: Color.fromRGBO(89, 131, 252, 1),
                height: 44,
                minWidth: 160,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(2)),
                  side: BorderSide(
                    width: 1,
                    color: Color.fromRGBO(89, 131, 252, 1),
                    style: BorderStyle.solid,
                  ),
                ),
                child: Text(
                  '上一条',
                  style: TextStyle(
                    fontSize: 14,
                    height: 24 / 17,
                  ),
                ),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.centerRight,
                  child: MaterialButton(
                    onPressed: () async {
                      if ((_formKey.currentState as FormState).validate()) {
                        print('提交');
                        final result =
                            await PrefUtil().openAlertDialog(context, '是否保存数据');
                        if (result == 'ok') {
                          saveInput('done');
                        }
                      }
                    },
                    color: Colors.blue,
                    textColor: Colors.white,
                    height: 44,
                    minWidth: 160,
                    child: Text(
                      '提交',
                      style: TextStyle(
                        fontSize: 14,
                        height: 24 / 17,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      }
    }
  }

  Future qrscan() async {
    try {
      String barcode = await scanner.scan();
      setState(() {
        _code.text = barcode;
      });
    } on FormatException {
      // NativeToast.show('已退出扫码');
    } catch (e) {
      // NativeToast.show('未知错误: $e');
    }
  }
}
